package game.utils;

import sys.io.Process;
import haxe.io.Path;
import js.node.ChildProcess;
import sys.io.File;
import haxe.Http;

class UpdateCore {
	/**
	 * 更新地址
	 */
	public static var updateUrl:String = "http://static.kdyx.cn/anime-battle-next/1000/update.zip";

	/**
	 * 应用程序路径
	 */
	public static var applicationPath(get, never):String;

	private static function get_applicationPath():String {
		var applicationPath = Sys.programPath();
		applicationPath = Path.directory(applicationPath);
		return applicationPath;
	}

	/**
	 * 热更流程
	 * @param cb 返回状态栏（0）更新完毕；（400）更新失败；（-1）更新错误
	 */
	public function new(cb:Int->Void) {
		trace("正在启动模块更新中...");
		var http = new Http(updateUrl + "?" + Math.random() + "&" + Std.random(999999));
		http.onStatus = function(data:Int) {
			if (data != 200) {
				cb(data);
			}
		};
		http.onBytes = function(data) {
			var savePath = applicationPath + "/app.zip";
			trace("保存至：" + savePath);
			File.saveBytes(savePath, data);
			// 解压
			var cmd = "cd " + applicationPath + "\nunzip -o app.zip\nrm -rf app.zip";
			if (Sys.systemName() == "Windows") {
				var cdto = applicationPath.charAt(0);
				cmd = cdto.toLowerCase() + ": & ";
				cmd += "cd " + applicationPath + " & zip\\unzip.exe -o app.zip"; // & rm -f app.zip
			}
			trace("cmd=", cmd);

			ChildProcess.exec(cmd, (error, stdout, stderrr) -> {
				trace("执行", stdout);
				trace("错误", stderrr);
				cb((error == null || error.code == 3221225477) ? 0 : error.code);
			});
		}
		http.request();
	}
}
